package design;

import java.util.LinkedHashMap;
public class LRU_146_2_7 {
    int cap;
    LinkedHashMap<Integer,Integer> cache = new LinkedHashMap<>();
    public LRU_146_2_7(int capacity) {
        this.cap = capacity;
    }
    public int get(int key) {
        if(!cache.containsKey(key)){
            return -1;
        }
        makeRecently(key);
        return cache.get(key);
    }
    public void put(int key, int value) {
        if(cache.containsKey(key)){
            // 覆盖值
            cache.put(key,value);
            makeRecently(key);
            return;
        }
        if(cap == cache.size()){
            Integer oldestKey = cache.keySet().iterator().next();
            cache.remove(oldestKey);
        }
        cache.put(key,value);
    }
    private void makeRecently(int key){
        Integer value = cache.get(key);
        cache.remove(key);
        cache.put(key,value);
    }






    public int get2(int key){
        if(!cache.containsKey(key)){
            return  -1;
        }
        makeRecently2(key);
        return cache.get(key);
    }
    public void put2(int key,int value){
        if(cache.containsKey(key)){
            cache.put(key,value);
            makeRecently2(key);
            return;
        }
        if(cache.size() == cap){
            Integer oldestKey = cache.keySet().iterator().next();
            cache.remove(oldestKey);
        }
        cache.put(key,value);
    }

    private void makeRecently2(int key){
        Integer value = cache.get(key);
        cache.remove(key);
        cache.put(key,value);
    }


}
